package Geral;

import entidade.Aluno;
import entidade.Curso;
import entidade.Diario;
import entidade.ManuAluno;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import persistencia.BD;

/**
 *
 * @author
 * Thomas Magnno Martins
 * Alexandre Junior Martins
 * Wanderson Ferreira
 */
public class ManutencaoAluno extends javax.swing.JFrame {

    Aluno aluno = new Aluno();

    public ManutencaoAluno() {
        initComponents();
        iniciar();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtMatricula = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtCpf = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cbCurso = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        cbEtapa = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaManutecao = new javax.swing.JTable();
        btnPesquisar = new javax.swing.JButton();
        btnLimpar = new javax.swing.JButton();
        btnGravarNota = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        banner = new javax.swing.JLabel();
        lblMensagem = new javax.swing.JLabel();
        btnSalvarAluno = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 706, 740));
        setMinimumSize(new java.awt.Dimension(720, 738));
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Arial", 1, 16));
        jLabel1.setForeground(new java.awt.Color(0, 102, 204));
        jLabel1.setText("Manutenção de Alunos");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 3, true), "Pesquisar", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 11))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel2.setText("Matricula : ");

        jLabel3.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel3.setText("CPF : ");

        jLabel4.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel4.setText("Nome : ");

        jLabel8.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel8.setText("Curso : ");

        jLabel9.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel9.setText("Etapa : ");

        cbEtapa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "1º Etapa", "2º Etapa", "3º Etapa" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(143, 143, 143)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel8)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbEtapa, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtNome, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(115, 115, 115))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cbCurso, cbEtapa});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(cbCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cbEtapa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9))))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cbCurso, cbEtapa, txtCpf, txtMatricula, txtNome});

        tabelaManutecao.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 3, true));
        tabelaManutecao.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID_Diario", "ID_Aluno", "ID_Curso", "ID_Materia", "Materia", "Nota", "Frequencia", "Situação"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaManutecao.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaManutecaoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaManutecao);

        btnPesquisar.setText("Pesquisar");
        btnPesquisar.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 2, true));
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        btnLimpar.setText("Limpar");
        btnLimpar.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 2, true));
        btnLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparActionPerformed(evt);
            }
        });

        btnGravarNota.setText("Gravar Nota");
        btnGravarNota.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 2, true));
        btnGravarNota.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGravarNotaActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 2, true));
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        banner.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Geral/banner.jpg"))); // NOI18N
        banner.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 2, true));

        lblMensagem.setForeground(new java.awt.Color(255, 0, 0));

        btnSalvarAluno.setText("Salvar Aluno");
        btnSalvarAluno.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 255), 2, true));
        btnSalvarAluno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarAlunoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(256, 256, 256)
                .addComponent(jLabel1)
                .addContainerGap(270, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblMensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
                .addGap(267, 267, 267))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGravarNota, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSalvarAluno, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE))
                .addContainerGap(25, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(banner, javax.swing.GroupLayout.PREFERRED_SIZE, 700, Short.MAX_VALUE)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnLimpar, btnPesquisar});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnGravarNota, btnSair});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(banner, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(9, 9, 9)
                .addComponent(lblMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSalvarAluno, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGravarNota, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(37, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnLimpar, btnPesquisar});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnGravarNota, btnSair});

        setBounds(150, 0, 709, 740);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed

        Menu menu = new Menu();
        menu.setVisible(true);
        this.dispose();

    }//GEN-LAST:event_btnSairActionPerformed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed


        BD banco = new BD();
        String sql = null;

        if (txtMatricula.getText().trim().equals("")) {
            lblMensagem.setText("O campo matricula é obrigatório!");

        }
        aluno.matricula = txtMatricula.getText();

        /* CORREÇÃO
        -   Quando utiliza * no select não é possível colocar , com as colunas com virgula
            solução: utilizar * com os labels das tabelas.
         *
         */
        sql = "SELECT al.*, d.*, m.*, c.*, nvl(IDDIARIO,'0')as idDiarioc FROM ALUNO AL  LEFT JOIN DIARIO D ON AL.IDALUNO = "
                + " D.ALUNO_IDALUNO LEFT JOIN MATERIA M ON D.IDMATERIA = "
                + " M.IDMATERIA LEFT JOIN CURSO C ON M.IDCURSO = C.IDCURSO "
                + " WHERE AL.MATRICULA_ALUNO = '" + aluno.matricula + "'";


        if (!txtNome.getText().trim().equals("")) {
            sql = sql + "AND upper(NOME_ALUNO) LIKE '%" + txtNome.getText().toUpperCase() + "%'";
        }

        if (!txtCpf.getText().trim().equals("")) {
            sql = sql + "AND CPF_ALUNO = '" + txtCpf.getText() + "'";
        }

        System.out.println(sql);

        try {

            ResultSet res;
            res = banco.consultar(sql);

            DefaultTableModel model = (DefaultTableModel) tabelaManutecao.getModel();

            int idCurso = -1;
            String etapa;

            while (res.next()) {
                int idDiario = res.getInt("IDDIARIO");

                // FORA DO IF, pois aluno sempre será recuperado.
                this.aluno.idaluno = res.getInt("idaluno");
                System.out.print("ID ALUNO: " + aluno.idaluno);

                // Preenche o diário apenas se o aluno estiver matriculado em alguma etapa
                // O teste é somente aqui, pois os dados do aluno sempre irão aparecer.
                if (idDiario != 0) {

                    Object[] linha = {res.getInt("IDDIARIO"),
                        res.getInt("IDALUNO"),
                        res.getInt("IDCURSO"),
                        res.getInt("IDMATERIA"),
                        res.getString("DESC_MATERIA"),
                        res.getString("NOTA_DIARIO"),
                        res.getString("FREQ_DIARIO"),
                        res.getString("SITUACAO_DIARIO")};
                    model.addRow(linha);
                }
                    idCurso = res.getInt("IDCURSO");
                    etapa = res.getString("ETAPA");

                    txtNome.setText(res.getString("NOME_ALUNO"));
                    txtCpf.setText(res.getString("CPF_ALUNO"));

                    DefaultComboBoxModel model1 = (DefaultComboBoxModel) cbEtapa.getModel();

                    DefaultComboBoxModel modelCurso = (DefaultComboBoxModel) cbCurso.getModel();

                    for (int i = 0; i < modelCurso.getSize(); i++) {
                        Curso temp = (Curso) modelCurso.getElementAt(i);
                        if (temp.getIdcurso() == idCurso) {
                            cbCurso.setSelectedIndex(i);
                        }
                    }

                    System.out.println(etapa);
                    for (int i = 0; i < model1.getSize(); i++) {
                        String elemento = (String) model1.getElementAt(i);
                        if (etapa != null && elemento != null && elemento.charAt(0) == etapa.charAt(0)) {
                            cbEtapa.setSelectedIndex(i);
                        }
                    }
                
               /*
                * CORRECAO
                * Código não necessário. Se não voltarem registros do banco, não é possível
                * obter os valores da coluna.
                * o if acima resolve essa questão.
                * 
                    if (res.next() == false) {
                        txtNome.setText(res.getString("NOME_ALUNO"));
                        txtCpf.setText(res.getString("CPF_ALUNO"));
                    }
               */

            }

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ManutencaoAluno.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ManutencaoAluno.class.getName()).log(Level.SEVERE, null, ex);
        }


        lblMensagem.setText("");





    }//GEN-LAST:event_btnPesquisarActionPerformed

    private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed

        txtMatricula.setText("");
        txtCpf.setText("");
        txtNome.setText("");
        cbCurso.setSelectedItem(null);
        cbEtapa.setSelectedItem(" ");

        DefaultTableModel model = (DefaultTableModel) tabelaManutecao.getModel();
        model.setRowCount(0);


    }//GEN-LAST:event_btnLimparActionPerformed

    private void btnGravarNotaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarNotaActionPerformed

        Aluno aluno = new Aluno();
        BD banco = new BD();
        Diario diario = new Diario();

        int linhaSelecionada = tabelaManutecao.getSelectedRow();

        DefaultTableModel model = (DefaultTableModel) tabelaManutecao.getModel();

        int iddiario = (Integer) model.getValueAt(linhaSelecionada, 0);
        String nota = (String) model.getValueAt(linhaSelecionada, 5);
        String freq = (String) model.getValueAt(linhaSelecionada, 6);
        String situ = (String) model.getValueAt(linhaSelecionada, 7);

        try {
            String sql = "UPDATE DIARIO SET "
                    + " NOTA_DIARIO = '" + nota + "',"
                    + " SITUACAO_DIARIO = '" + situ + "',"
                    + " FREQ_DIARIO = '" + freq + "'"
                    + " WHERE IDDIARIO ='" + iddiario + "'";

            System.out.println(sql);
            banco.executar(sql, new Object[0], new Object[0]);
        } catch (Exception ex) {
            Logger.getLogger(ManutencaoAluno.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(this, "Notas Gravadas com Sucesso");









    }//GEN-LAST:event_btnGravarNotaActionPerformed

    private void tabelaManutecaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaManutecaoMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_tabelaManutecaoMouseClicked

    private void btnSalvarAlunoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarAlunoActionPerformed

        // CORRECAO
        // Aluno passou a ser uma variável global, para que não sejam perdidos seus dados
        // de um método pra outro
        
        BD banco = new BD();
        Curso idcurso = (Curso) cbCurso.getSelectedItem();
        String etapa = (String) cbEtapa.getSelectedItem();
        aluno.matricula = txtMatricula.getText();

        try {
            String sql = "UPDATE ALUNO SET "
                    + " CURSO_IDCURSO = ?, "
                    + " ETAPA = ?"
                    + " WHERE MATRICULA_ALUNO = '" + aluno.matricula + "'";

            Object[] parametros = {idcurso.getIdcurso(), etapa};
            Object[] tipos = {Integer.class, String.class};

            banco.executar(sql, parametros, tipos);


            String sqlDois = "select * from materia where IDCURSO = '" + idcurso.getIdcurso() + "' and etapa = '" + etapa + "'";
            System.out.println(sqlDois);
            ResultSet res;
            res = banco.consultar(sqlDois);


            while (res.next()) {

                int idmateria = res.getInt("IDMATERIA");
                int idcur = res.getInt("IDCURSO");

                String sqlTres = " INSERT INTO DIARIO (IDDIARIO, IDMATERIA, CURSO_IDCURSO, ALUNO_IDALUNO) "
                        + " VALUES(SQ_DIARIO.NEXTVAL, ? , ?, ?)";
                System.out.println(sqlTres + "," + idmateria + "," + idcur + "," + this.aluno.idaluno);
                Object[] parametrosTres = {idmateria, idcur, this.aluno.idaluno};
                Object[] tiposTres = {Integer.class, Integer.class, Integer.class};

                banco.executar(sqlTres, parametrosTres, tiposTres);

            }

            String sqlQuatro = "select * from materia m join CURSO cu on m.idcurso = cu.idcurso"
                    + " join aluno al on cu.idcurso = al.curso_idcurso"
                    + " join diario d on al.idaluno = d.aluno_idaluno" // ESSE JOIN ESTAVA FALTANDO
                    + " where al.idaluno =" + this.aluno.idaluno
                    + " and m.etapa = '" + cbEtapa.getSelectedItem() + "'";  // Filtro que busca apenas materias da etapa selecionada

            res = banco.consultar(sqlQuatro);
            DefaultTableModel model = (DefaultTableModel) tabelaManutecao.getModel();

            while (res.next()) {
                Object[] linha = {res.getInt("IDDIARIO"),
                    res.getInt("IDALUNO"),
                    res.getInt("CURSO_IDCURSO"),
                    res.getInt("IDMATERIA"),
                    res.getString("DESC_MATERIA"),
                    res.getString("NOTA_DIARIO"),
                    res.getString("FREQ_DIARIO"),
                    res.getString("SITUACAO_DIARIO")};
                model.addRow(linha);
            }
            //  select   em aluno diario e materia where matricula
            // salvar em res
            // pegar o model
            // fazer while para preencher a tabela


        } catch (Exception ex) {
            Logger.getLogger(ManutencaoAluno.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(this, "Alteração efetuada com Sucesso");


    }//GEN-LAST:event_btnSalvarAlunoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ManutencaoAluno().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel banner;
    private javax.swing.JButton btnGravarNota;
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSalvarAluno;
    private javax.swing.JComboBox cbCurso;
    private javax.swing.JComboBox cbEtapa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMensagem;
    private javax.swing.JTable tabelaManutecao;
    private javax.swing.JTextField txtCpf;
    private javax.swing.JTextField txtMatricula;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables

    public void iniciar() {
        try {
            String sql = "SELECT * FROM CURSO";
            BD banco = new BD();
            banco.consultar(sql);

            ResultSet res = banco.consultar(sql);
            Curso curs = new Curso();
            cbCurso.addItem(curs);
            while (res.next()) {

                Curso curso = new Curso();
                curso.setIdcurso(res.getInt("IDCURSO"));
                curso.desc_curso = res.getString("DESC_CURSO");
                cbCurso.addItem(curso);


            }




        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ManutencaoAluno.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ManutencaoAluno.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
